﻿namespace com.crownpack.Extensions.SharePointExtensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Microsoft.BusinessData.MetadataModel;

    /// <summary>
    /// References the following:
    /// ...\14\ISAPI\Microsoft.BusinessData.dll
    /// </summary>
    public static class IMetadataCatalogExtensions
    {
        #region Methods

        /// <summary>
        /// Gets the entity with the given name and namespace. The namespace is case sensitive, however the entity name is case insensitive. Initially, an attempt is made to get the entity with the case sensitive given name. If the entity is not found, an attempt is made with the case insensitive given name. Note: This could create anomalies if multiple entities exist with the same name in different cases.
        /// </summary>
        /// <param name="catalog">Represents an entry point for the run-time functionality.</param>
        /// <param name="namespace">The given namespace. Namespace strings are case sensitive.</param>
        /// <param name="name">The given entity name. The entity name is case insensitive.</param>
        /// <returns>Returns the entity if found, otherwise returns null.</returns>
        public static IEntity TryGetEntity( this IMetadataCatalog catalog, string @namespace, string name )
        {
            IEntity entity = null;
            List<KeyValuePair<string, IEntity>> entities = catalog.GetEntities( @namespace, "*" ).ToList( );
            int i = entities.FindIndex( a => a.Value.Name.Equals( name ) );
            if ( i <= -1 )
                i = entities.FindIndex( a => a.Value.Name.Equals( name, StringComparison.OrdinalIgnoreCase ) );
            if ( i >= 0 )
            {
                KeyValuePair<string, IEntity> n = entities[ i ];
                entity = n.Value;
            }
            return entity;
        }

        #endregion Methods
    }
}